using System.Collections.Generic;
using System.IO;
using QFramework;
using UnityEngine;
using Utilities;

public class CardData : AbstractModel
{
    private string obtainedCardsFilePath = "";

    public List<Card> Cards { get; set; } = new List<Card>();

    /// <summary>
    /// 获得的卡牌，<卡牌ID, 张数>
    /// </summary>
    public Dictionary<int, int> ObtainedCards { get; set; } = new Dictionary<int, int>();

    protected override void OnInit()
    {
        obtainedCardsFilePath = Application.dataPath + Definitions.ObtainedCardsPath;

        Debug.Log(Application.dataPath);
        Debug.Log(Application.streamingAssetsPath);

        LoadCardData();
        LoadObtainedCards();
    }

    public void LoadCardData()
    {
        var cardData = Resources.Load<TextAsset>("Data/CardData");
        string[] dataRow = cardData.text.Split('\n');

        foreach (string row in dataRow)
        {
            var rowArray = row.Split(',');
            if (rowArray[0] == "类型")
                continue;
            if (rowArray.Length != 11)
                continue;

            int id = int.Parse(rowArray[1]);
            string name = rowArray[2];
            string description = rowArray[3];
            int cost = int.Parse(rowArray[4]);
            int health = 0;
            if (int.TryParse(rowArray[9], out int tempHealth))
            {
                health = tempHealth;
            }
            int attack = int.Parse(rowArray[10]);

            switch (rowArray[0])
            {
                case nameof(MonsterCard):
                    var monsterCard = new MonsterCard();
                    monsterCard.Id = id;
                    monsterCard.Name = name;
                    monsterCard.Description = description;
                    monsterCard.Cost = cost;
                    monsterCard.Health = health;
                    monsterCard.Attack = attack;
                    this.Cards.Add(monsterCard);
                    break;
                case nameof(SpellCard):
                    var spellCard = new SpellCard();
                    spellCard.Id = id;
                    spellCard.Name = name;
                    spellCard.Description = description;
                    spellCard.Cost = cost;
                    this.Cards.Add(spellCard);
                    break;
            }
        }
    }

    public void LoadObtainedCards()
    {
        if (!File.Exists(obtainedCardsFilePath))
            return;
        
        string info = File.ReadAllText(obtainedCardsFilePath);
        this.ObtainedCards = SerializeDictionary.FromJson<int, int>(info);
    }

    public void SaveObtainedCards()
    {
        string info = SerializeDictionary.ToJson(ObtainedCards);
        File.WriteAllText(obtainedCardsFilePath, info);
    }
}
